﻿using Newtonsoft.Json;
using SHKF.B2C.Model;
using SHKF.B2C.Model.Dto;
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;

namespace SHKF.B2C.Network
{
    public class HttpClientBase : HttpClient
    {
        public async Task<T> GetAsync<T>(string requestUri, Dictionary<string, object> paramList = null) where T : ErrorDto, new()
        {
            string url = GetUrl(requestUri);

            if (paramList != null && paramList.Count > 0)
            {
                url += "?";
                string strParam = "";
                foreach (KeyValuePair<string, object> keyValue in paramList)
                {
                    if (strParam != "")
                    {
                        strParam += "&";
                    }

                    strParam += $"{keyValue.Key}={keyValue.Value}";
                }
                url += strParam;
            }

            HttpResponseMessage httpResponseMessage = await base.GetAsync(url);
            if (!httpResponseMessage.IsSuccessStatusCode)
            {
                T dto = new T();
                dto.SetError(httpResponseMessage);

                return dto;
            }
            else
            {
                string result = await httpResponseMessage.Content.ReadAsStringAsync();
                return await httpResponseMessage.Content.ReadAsAsync<T>();
            }
        }
        public async Task<T> PostAsync<T>(string requestUri, object data) where T : ErrorDto, new()
        {
            T dto = new T();
            string json = JsonConvert.SerializeObject(data);
            StringContent stringContent = new StringContent(json);
            stringContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");

            HttpResponseMessage httpResponseMessage = await base.PostAsync(requestUri, stringContent);
            if (httpResponseMessage.IsSuccessStatusCode)
            {
                dto = await httpResponseMessage.Content.ReadAsAsync<T>();
            }
            else
            {
                dto = new T();
                dto.SetError(httpResponseMessage);
            }
            return dto;
        }
        private string GetUrl(string requestUri)
        {
            string url = base.BaseAddress.OriginalString + requestUri;
            if (!string.IsNullOrEmpty(requestUri) && requestUri.ToLower().Contains("http"))
            {
                url = requestUri;
            }
            return url;
        }

    }
}
